package src.dp.easy;

import java.util.Arrays;

public class no64 {//最小路径和

    /**
     * 1. 确定dp数组下标含义：到达[i][j]位置 的路径最小和是 dp[i][j]
     * 2. 递推公式：dp[i][j] = grid[i][j] + Math.min(dp[i-1][j], dp[i][j-1])
     * 3. 初始化数组：初始化第0行 第0列
     * 4. 遍历顺序：逐行 逐列都行
     */
    public static void main(String[] args) {
        int[][] arr = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}};
        int res = minPathSum(arr);
        System.out.println(res);
    }

    public static int minPathSum(int[][] grid) {
        int m = grid.length;  //m行
        int n = grid[0].length;  //n列

        int[][] dp = new int[m][n];
        dp[0][0] = grid[0][0];

        for (int i = 1; i < m; i++) {
            dp[i][0] = dp[i - 1][0] + grid[i][0];
        }

        for (int j = 1; j < n; j++) {
            dp[0][j] = grid[0][j] + dp[0][j - 1];
        }

        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[i][j] = Math.min(dp[i - 1][j] + grid[i][j], dp[i][j - 1] + grid[i][j]);
            }
        }

        return dp[m - 1][n - 1];


    }
}
